/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Persistencia;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Logica.Marca;
import Logica.Modelo;
import Logica.Segmento;
import Persistencia.exceptions.NonexistentEntityException;
import Persistencia.exceptions.PreexistingEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Pablo
 */
public class ModeloJpaController implements Serializable {

      public ModeloJpaController(){
        emf = Persistence.createEntityManagerFactory("TpFinalPU");
    }
    public ModeloJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Modelo modelo) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Marca unaMarca = modelo.getUnaMarca();
            if (unaMarca != null) {
                unaMarca = em.getReference(unaMarca.getClass(), unaMarca.getNombre());
                modelo.setUnaMarca(unaMarca);
            }
            Segmento unSegmento = modelo.getUnSegmento();
            if (unSegmento != null) {
                unSegmento = em.getReference(unSegmento.getClass(), unSegmento.getNombre());
                modelo.setUnSegmento(unSegmento);
            }
            em.persist(modelo);
            if (unaMarca != null) {
                unaMarca.getModelos().add(modelo);
                unaMarca = em.merge(unaMarca);
            }
            if (unSegmento != null) {
                unSegmento.getModelos().add(modelo);
                unSegmento = em.merge(unSegmento);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findModelo(modelo.getNombre()) != null) {
                throw new PreexistingEntityException("Modelo " + modelo + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Modelo modelo) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Modelo persistentModelo = em.find(Modelo.class, modelo.getNombre());
            Marca unaMarcaOld = persistentModelo.getUnaMarca();
            Marca unaMarcaNew = modelo.getUnaMarca();
            Segmento unSegmentoOld = persistentModelo.getUnSegmento();
            Segmento unSegmentoNew = modelo.getUnSegmento();
            if (unaMarcaNew != null) {
                unaMarcaNew = em.getReference(unaMarcaNew.getClass(), unaMarcaNew.getNombre());
                modelo.setUnaMarca(unaMarcaNew);
            }
            if (unSegmentoNew != null) {
                unSegmentoNew = em.getReference(unSegmentoNew.getClass(), unSegmentoNew.getNombre());
                modelo.setUnSegmento(unSegmentoNew);
            }
            modelo = em.merge(modelo);
            if (unaMarcaOld != null && !unaMarcaOld.equals(unaMarcaNew)) {
                unaMarcaOld.getModelos().remove(modelo);
                unaMarcaOld = em.merge(unaMarcaOld);
            }
            if (unaMarcaNew != null && !unaMarcaNew.equals(unaMarcaOld)) {
                unaMarcaNew.getModelos().add(modelo);
                unaMarcaNew = em.merge(unaMarcaNew);
            }
            if (unSegmentoOld != null && !unSegmentoOld.equals(unSegmentoNew)) {
                unSegmentoOld.getModelos().remove(modelo);
                unSegmentoOld = em.merge(unSegmentoOld);
            }
            if (unSegmentoNew != null && !unSegmentoNew.equals(unSegmentoOld)) {
                unSegmentoNew.getModelos().add(modelo);
                unSegmentoNew = em.merge(unSegmentoNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = modelo.getNombre();
                if (findModelo(id) == null) {
                    throw new NonexistentEntityException("The modelo with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Modelo modelo;
            try {
                modelo = em.getReference(Modelo.class, id);
                modelo.getNombre();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The modelo with id " + id + " no longer exists.", enfe);
            }
            Marca unaMarca = modelo.getUnaMarca();
            if (unaMarca != null) {
                unaMarca.getModelos().remove(modelo);
                unaMarca = em.merge(unaMarca);
            }
            Segmento unSegmento = modelo.getUnSegmento();
            if (unSegmento != null) {
                unSegmento.getModelos().remove(modelo);
                unSegmento = em.merge(unSegmento);
            }
            em.remove(modelo);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Modelo> findModeloEntities() {
        return findModeloEntities(true, -1, -1);
    }

    public List<Modelo> findModeloEntities(int maxResults, int firstResult) {
        return findModeloEntities(false, maxResults, firstResult);
    }

    private List<Modelo> findModeloEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Modelo.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Modelo findModelo(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Modelo.class, id);
        } finally {
            em.close();
        }
    }

    public int getModeloCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Modelo> rt = cq.from(Modelo.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
